package edu.umd.ion.wavemeter.server;

import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.TreeMap;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;

public class PIDCourseOracle {
	private EntityManagerFactory emf;
	private TreeMap<String,PersistentPIDCourseData> ByCourse;
	
	@SuppressWarnings("unchecked")
	public PIDCourseOracle() {
		emf =  WavemeterConfiguration.createEntityManagerFactory();
		EntityManager em = emf.createEntityManager();
		Query q = em.createNamedQuery("all_pidcoursedata");
		List<PersistentPIDCourseData> results = q.getResultList();
		Iterator<PersistentPIDCourseData> I = results.iterator();
		ByCourse = new TreeMap<String,PersistentPIDCourseData>();
		while (I.hasNext()) {
			PersistentPIDCourseData D = I.next();
			ByCourse.put(D.Course,D);
		}
		em.close();
	}
	
	synchronized private void store(PersistentPIDCourseData Data) {
		EntityManager em = emf.createEntityManager();
		em.getTransaction().begin();
		PersistentPIDCourseData found = em.find(PersistentPIDCourseData.class, Data.getPrimaryKey() );
		if (found==null) { 
			em.persist(Data); 
		} else {
			found.set(Data);
		}
		em.getTransaction().commit();
		em.close();
	}
	
	synchronized public void addCourse(String Course, long usagetime, int channel) {
		PersistentPIDCourseData Data = ByCourse.get(Course);
		if (Data==null) {
			Data = new PersistentPIDCourseData();
			Data.Course = Course;
		}
		Data.TimeUsed += usagetime;
		Data.LastUsed = new Date( System.currentTimeMillis() );
		ByCourse.put(Course, Data);
		store(Data);
	}
	
	synchronized public String[] getSuggestions(int channel) {
		return ByCourse.keySet().toArray(new String[ByCourse.size()]);
	}
}
